package com.tanhua.dubbo.api;

import com.tanhua.model.mongo.Comment;
import com.tanhua.model.mongo.Movement;
import com.tanhua.model.mongo.Video;
import com.tanhua.model.mongo.VideoComment;
import com.tanhua.model.vo.PageResult;
import com.tanhua.model.vo.VideoCommentVo;
import org.apache.dubbo.config.annotation.DubboService;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.FindAndModifyOptions;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;

import java.util.List;

@DubboService
public class VideoCommentApiImpl implements VideoCommentApi {

    @Autowired
    private MongoTemplate mongoTemplate;

    /**
     *判断用户是否已经进行了点赞
     */
    @Override
    public Boolean hasLike(Long userId, ObjectId videoId, Integer videoType) {
        Criteria criteria = Criteria.where("publishId").is(videoId)
                .and("commentType").is(videoType)
                .and("userId").is(userId);
        return mongoTemplate.exists(Query.query(criteria), VideoComment.class);
    }


    /**
     * 保存用户数据
     */
    @Override
    public void save(VideoComment videoComment) {
        mongoTemplate.save(videoComment);
    }

    /**
     * 删除点赞数据
     */
    @Override
    public void delComment(String videoId, Integer videoType, Long userId) {
        Criteria criteria = Criteria.where("publishId").is(new ObjectId(videoId))
                .and("commentType").is(videoType)
                .and("userId").is(userId);

        mongoTemplate.remove(Query.query(criteria),VideoComment.class);
    }

    @Override
    public List<VideoComment> findComments(Integer page, Integer pagesize, String videoId, Integer commentType) {
        Criteria criteria = Criteria.where("publishId").is(new ObjectId(videoId))
                .and("commentType").is(commentType);
        Query query = Query.query(criteria)
                .with(Sort.by(Sort.Order.desc("created")))
                .skip((page - 1) * pagesize)
                .limit(pagesize);
        return mongoTemplate.find(query,VideoComment.class);

    }

    @Override
    public void saveVideoComments(VideoComment videoComment) {
        ObjectId publishId = videoComment.getPublishId();
        Video video = mongoTemplate.findById(publishId, Video.class);
        videoComment.setPublishUserId(video.getUserId());
        mongoTemplate.save(videoComment);

        Update update = new Update();//更新的字段
        if(videoComment.getCommentType() == 1) {
            update.inc("likeCount",1);
        }else {
            update.inc("commentCount",1);
        }
        FindAndModifyOptions options = new FindAndModifyOptions();
        options.returnNew(true); // 更新之后返回最新结果


    }
}
